package com.cz.video.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.cz.video.common.constant.CacheConstants;
import com.cz.video.common.constant.Constants;
import com.cz.video.common.constant.UserConstants;
import com.cz.video.common.core.domain.R;
import com.cz.video.common.exception.ServiceException;
import com.cz.video.common.utils.email.MailUtils;
import com.cz.video.common.utils.redis.RedisUtils;
import com.cz.video.framework.config.properties.MailProperties;
import com.cz.video.system.api.RemoteUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.time.Duration;

/**
 * 验证码操作处理
 *
 * @author cz
 */
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController {

    private final MailProperties mailProperties;
    @DubboReference
    private final RemoteUserService remoteUserService;

    /**
     * 邮箱验证码
     *
     * @param email 邮箱
     */
    @GetMapping("/captchaEmail")
    public R<Void> emailCode(@NotBlank(message = "邮箱不能为空") String email,String businessType) {
        if (!mailProperties.getEnabled()) {
            return R.fail("当前系统没有开启邮箱功能！");
        }
        //检查邮箱是否存在
        if (UserConstants.EMAIL_TYPE_REGISTER.equals(businessType)){
            if (remoteUserService.selectUserByEmail(email)!=null) {
                throw new ServiceException("该邮箱已绑定给其他账户");
            }
        }
        String key = CacheConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        try {
            MailUtils.sendText(email, "登录验证码", "您本次验证码为：" + code + "，有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟，请尽快填写。");
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

}
